<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-row :gutter="20">
                <el-col :span="12">宠物管理</el-col>
                <el-col :span="12" class="text-right">
                    <el-button type="primary" @click="showAddDrawer">添加宠物</el-button>
                </el-col>
            </el-row>
        </template>

        <!-- 搜索栏 -->
        <div>
            <el-form :inline="true" :model="searchForm" class="responsive-form">
                <el-form-item label="宠物分类">
                    <el-select v-model="searchForm.category" default-first-option filterable @change="handleSearch"
                        style="min-width: 120px;">
                        <el-option label="全部" value="全部"></el-option>
                        <el-option v-for="category in categories" :key="category" :label="category"
                            :value="category"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="宠物名称">
                    <el-input v-model="searchForm.name" placeholder="请输入宠物名称" @keyup.enter="handleSearch"
                        style="min-width: 200px;"></el-input>
                </el-form-item>

                <el-form-item class="form-buttons">
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 宠物表格 -->
            <el-table :data="pets" v-loading="loading" style="width: 100%">
                <el-table-column fixed label="ID" prop="id" width="80"></el-table-column>
                <el-table-column label="全名" prop="全名" min-width="120"></el-table-column>
                <el-table-column label="别名" prop="别名" min-width="120"></el-table-column>
                <el-table-column label="分类" prop="分类" width="100"></el-table-column>
                <el-table-column label="体型" prop="体型" width="100"></el-table-column>
                <el-table-column label="毛发" prop="毛发" width="100"></el-table-column>
                <el-table-column label="智商" prop="智商" width="80"></el-table-column>
                <el-table-column label="寿命" prop="寿命" width="80"></el-table-column>
                <el-table-column label="价格" prop="价格" width="100"></el-table-column>
                <el-table-column label="原产地" prop="原产地" min-width="120"></el-table-column>
                <el-table-column label="简介" prop="简介" min-width="200">
                    <template #default="{ row }">
                        <el-popover
                            placement="top-start"
                            trigger="hover"
                            :width="300"
                        >
                            <template #default>
                                <div style="white-space: pre-wrap;">{{ row.简介 }}</div>
                            </template>
                            <template #reference>
                                <div class="truncate-text">{{ row.简介 }}</div>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="180">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="PAGE_SIZE"
                :total="totalPets" layout="total, prev, pager, next" class="mt-4"></el-pagination>
        </div>

        <!-- 宠物添加/编辑抽屉 -->
        <el-drawer v-model="drawerVisible" :title="drawerTitle" size="50%" direction="rtl" :destroy-on-close="true">
            <AddAnimalSet v-if="dialogType === 'add'" @cancel="handleCancel" @success="handleSuccess" />
            <EditAnimalSet v-if="dialogType === 'edit' && drawerVisible" :key="currentPet?.id" :petData="currentPet" @cancel="handleCancel"
                @success="handleSuccess" />
        </el-drawer>
    </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddAnimalSet from './addAnimalSet.vue';
import EditAnimalSet from './editAnimalSet.vue';
import { getPets, getPetCategories, deletePet } from '@/api/admin';

// 常量
const PAGE_SIZE = 20;

// 数据定义
const pets = ref([]);
const categories = ref([]);
const loading = ref(false);
const drawerVisible = ref(false);
const dialogType = ref('add');
const currentPet = ref(null);
const currentPage = ref(1);
const totalPets = ref(0);

const searchForm = ref({
    category: '全部',
    name: ''
});

// 计算属性
const drawerTitle = computed(() => {
    return dialogType.value === 'add' ? '添加宠物' : '编辑宠物';
});

// 方法定义
const fetchPets = async () => {
    loading.value = true;
    try {
        const { data } = await getPets(searchForm.value.category, currentPage.value, searchForm.value.name);
        if (data.code === 200) {
            pets.value = data.data;
            totalPets.value = data.total;
        } else {
            ElMessage.error(data.message || '获取宠物列表失败');
        }
    } catch (error) {
        ElMessage.error('获取宠物列表失败：' + error.message);
    } finally {
        loading.value = false;
    }
};

const fetchCategories = async () => {
    try {
        const { data } = await getPetCategories();
        if (data.code === 200) {
            categories.value = data.data;
        } else {
            ElMessage.error(data.message || '获取分类信息失败');
        }
    } catch (error) {
        ElMessage.error('获取分类信息失败：' + error.message);
    }
};

const handleSearch = () => {
    currentPage.value = 1;
    fetchPets();
};

const handleReset = () => {
    searchForm.value.category = '全部';
    searchForm.value.name = '';
    handleSearch();
    fetchCategories(); // 刷新分类列表
    fetchPets(); // 刷新宠物列表
};

const handlePageChange = (page) => {
    currentPage.value = page;
    fetchPets();
};

const showAddDrawer = () => {
    dialogType.value = 'add';
    drawerVisible.value = true;
};

const handleEdit = (row) => {
    dialogType.value = 'edit';
    // 创建一个新的对象来避免引用问题
    currentPet.value = JSON.parse(JSON.stringify(row));
    drawerVisible.value = true;
};

const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除这个宠物吗？', '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            const { data } = await deletePet(row.id);
            if (data.code === 200) {
                ElMessage.success('删除成功');
                fetchPets();
            } else {
                ElMessage.error(data.message || '删除失败');
            }
        } catch (error) {
            ElMessage.error('删除失败：' + error.message);
        }
    }).catch(() => { });
};

const handleSuccess = () => {
    drawerVisible.value = false;
    fetchCategories(); // 刷新分类列表
    fetchPets(); // 刷新宠物列表
};

const handleCancel = () => {
    drawerVisible.value = false;
    currentPet.value = null;
};

// 生命周期钩子
onMounted(() => {
    fetchPets();
    fetchCategories();
});
</script>

<style scoped>
.text-right {
    text-align: right;
}

.mt-4 {
    margin-top: 1rem;
}

.truncate-text {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.5;
    max-height: 3em;
    will-change: transform;
}

/* 添加表格滚动优化 */
:deep(.el-table__body-wrapper) {
    overflow-y: auto;
    scrollbar-width: thin;
}

:deep(.el-table) {
    transform: translateZ(0);
}

.responsive-form {
    display: flex;
    flex-wrap: wrap;
}

.form-buttons {
    margin-left: 0 !important;
    margin-top: 10px;
}

@media (max-width: 768px) {
    .el-form-item {
        margin-right: 0 !important;
        width: 100%;
    }
    
    .el-select {
        width: 100%;
    }
    
    .el-button {
        width: 100%;
        margin-bottom: 10px;
    }
}
</style>